<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Cookie;
use wxpay\database\WxPayUnifiedOrder;
use wxpay\JsApiPay;
use wxpay\NativePay;
use wxpay\PayNotifyCallBack;
use think\Log;
use wxpay\WxPayApi;
use wxpay\WxPayConfig;
use alipay\wappay\buildermodel\AlipayTradeWapPayContentBuilder;
use alipay\wappay\service\AlipayTradeService;
use pinganpay\Webapp;

class Pay extends Controller {

	private $resHandler;
	private $reqHandler;
	private $pay;
	private $cfg;

	/**
	 * 微信支付
	 * @return [type] [description]
	 */
	public function wxpay($data) {


		if (!empty($data)) {
			//获取用户openid
			$tools = new JsApiPay();
			$openId = Db::name('userinfo')->where(array('uid' => $data['uid']))->value('openid');

			if (!$openId) {
				return WPreturn('openId不存在', -1);
			}
			//统一下单
			$input = new WxPayUnifiedOrder();
			$input->setBody("会员余额充值");
			$input->setAttach("web_user_pay_ing");

			$input->setOutTradeNo($data['balance_sn']);
			$input->setTotalFee($data['bpprice'] * 100);
			$input->setTimeStart(date("YmdHis"));
			$input->setTimeExpire(date("YmdHis", time() + 600));
			$input->setGoodsTag("goods");
			$input->setNotifyUrl("http://" . $_SERVER['SERVER_NAME'] . "/index/wechat/notifyurl/bpid/" . $data['bpid']);
			$input->setTradeType("JSAPI");
			$input->setOpenid($openId);

			$order = WxPayApi::unifiedOrder($input);

			$jsApiParameters = $tools->getJsApiParameters($order);

			/*
			  $this->assign('order',$order);
			  $this->assign('jsApiParameters',$jsApiParameters);
			  return $this->fetch('jsapi');
			 */
			return $jsApiParameters;
		}
	}

	/**
	 * 中云支付
	 * @return [type] [description]
	 */
	public function zypay($data) {


		$pay_memberid = "11580";   //商户ID
		$pay_orderid = $data['balance_sn']; //订单号
		$pay_amount = $data['bpprice']; //交易金额
		$pay_applydate = date("Y-m-d H:i:s");  //订单时间
		$pay_bankcode = "WftZfb";   //银行编码
		$pay_notifyurl = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/zypay_notify.html";   //服务端返回地址
		$pay_callbackurl = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html";  //页面跳转返回地址

		$Md5key = "FYXPPTVr3Hwk5vhjZOl2kPHyT3kWoM";   //密钥

		$tjurl = "http://zy.cnzypay.com/Pay_Index.html";   //提交地址,如有变动请到官网下载最新接口文档

		$requestarray = array(
			"pay_memberid" => $pay_memberid,
			"pay_orderid" => $pay_orderid,
			"pay_amount" => $pay_amount,
			"pay_applydate" => $pay_applydate,
			"pay_bankcode" => $pay_bankcode,
			"pay_notifyurl" => $pay_notifyurl,
			"pay_callbackurl" => $pay_callbackurl,
			'tongdao' => 1
		);

		ksort($requestarray);
		reset($requestarray);
		$md5str = "";
		foreach ($requestarray as $key => $val) {
			$md5str = $md5str . $key . "=>" . $val . "&";
		}

		$sign = strtoupper(md5($md5str . "key=" . $Md5key));
		$requestarray["pay_md5sign"] = $sign;

		$str = '<form id="Form1" name="Form1" method="post" action="' . $tjurl . '">';
		foreach ($requestarray as $key => $val) {
			$str = $str . '<input type="hidden" name="' . $key . '" value="' . $val . '">';
		}
		$str = $str . '<input type="submit" value="提交">';
		$str = $str . '</form>';
		$str = $str . '<script>';
		$str = $str . 'document.Form1.submit();';
		$str = $str . '</script>';

		return $str;
	}

	public function zypay_notify() {

		$ReturnArray = array(// 返回字段
			"memberid" => $_REQUEST["memberid"], // 商户ID
			"orderid" => $_REQUEST["orderid"], // 订单号
			"amount" => $_REQUEST["amount"], // 交易金额
			"datetime" => $_REQUEST["datetime"], // 交易时间
			"returncode" => $_REQUEST["returncode"]
		);

		$Md5key = "FYXPPTVr3Hwk5vhjZOl2kPHyT3kWoM";
		//$sign = $this->md5sign($Md5key, $ReturnArray);
		///////////////////////////////////////////////////////
		ksort($ReturnArray);
		reset($ReturnArray);
		$md5str = "";
		foreach ($ReturnArray as $key => $val) {
			$md5str = $md5str . $key . "=>" . $val . "&";
		}
		$sign = strtoupper(md5($md5str . "key=" . $Md5key));
		///////////////////////////////////////////////////////
		if ($sign == $_REQUEST["sign"]) {
			if ($_REQUEST["returncode"] == "00") {
				$this->notify_ok_dopay($ReturnArray['orderid'], $ReturnArray['amount']);
				exit("ok");
			}
		}

		cache('');
	}

	public function qianbaotong($data, $pay_type) {


		/*
		 * 商户id，由平台分配
		 */
		$parter = 1729;

		/*
		 * 准备使用网银支付的银行
		 */
		$type = $pay_type;

		/*
		 * 支付金额
		 */
		$value = $data['bpprice'];

		/*
		 * 请求发起方自己的订单号，该订单号将作为平台的返回数据
		 */
		$orderid = $data['balance_sn'];

		/*
		 * 在下行过程中返回结果的地址，需要以http://开头。
		 */
		$callbackurl = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/qdb_notify.html";
		;

		/*
		 * 支付完成之后平台会自动跳转回到的页面
		 */
		$hrefbackurl = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html";
		;

		/*
		 * 商户密钥
		 */
		$key = '3177204082c74e4db0f24ae2d5290617';


		$shidai_bank_url = 'http://gateway.qpabc.com/bank/index.aspx';

		$url = "parter=" . $parter . "&type=" . $type . "&value=" . $value . "&orderid=" . $orderid . "&callbackurl=" . $callbackurl;
		//签名
		$sign = md5($url . $key);

		//最终url
		$url = $shidai_bank_url . "?" . $url . "&sign=" . $sign . "&hrefbackurl=" . $hrefbackurl;

		if (in_array($pay_type, array(1005, 1006, 1007))) {
			return $url;
		} else {
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_TIMEOUT, 500);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_URL, $url);

			$res = curl_exec($curl);
			curl_close($curl);

			return $res;
		}
	}

	public function qdb_notify() {
		cache('qdb_test', $_GET);
		//$_GET = cache('qdb_test');
		//获取返回的下行数据
		//$sysorderid     = trim($_GET['sysorderid']);
		//$completiontime     = trim($_GET['systime']);
		//进行爱扬签名认证
		$key = '3177204082c74e4db0f24ae2d5290617';
		header('Content-Type:text/html;charset=GB2312');
		$orderid = trim($_GET['orderid']);
		$opstate = trim($_GET['opstate']);
		$ovalue = trim($_GET['ovalue']);
		$sign = trim($_GET['sign']);

		//订单号为必须接收的参数，若没有该参数，则返回错误
		if (empty($orderid)) {
			die("opstate=-1");   //签名不正确，则按照协议返回数据
		}

		$sign_text = "orderid=$orderid&opstate=$opstate&ovalue=$ovalue" . $key;
		$sign_md5 = md5($sign_text);
		if ($sign_md5 != $sign) {
			die("opstate=-2");   //签名不正确，则按照协议返回数据
		}
		$this->notify_ok_dopay($orderid, $ovalue);
		die("opstate=0");
	}

	public function alipay($data) {

		$config = array(
			//应用ID,您的APPID。
			'app_id' => "2017022705923867",
			//商户私钥，您的原始格式RSA私钥
			'merchant_private_key' => "MIIEowIBAAKCAQEA4SvhwaggPK6YcT9KFcWatlWzmPOGuinPibsSuQOKOzIdndmsobx8gxYsL40SBJZJ7gUzLW53WUPJiu1Cn2K6b1m/PsOQNl6WRQD7fD62fCO5z3Wqitx9bts/LoUbX7vb4Dxpplw7KKVikUCBwe75hOTuhAfQ7dqGzbE0xfKjO2ugRBDceCy5InBK/xfvVbNRk+1DZyexLSUJx7pm5nUCkVj81URlnQYzcW06OBjvSSecTpmAktbvruZE450vhxkfDzxp47R0qba4c8ALRrDlnrUb29EPD4TFmXWGxteZQBQWKbEJWte7tV/sGW9ed/6QeC8A9N3CalnzXpqIF4hpcQIDAQABAoIBAFOUPDnrs/uSOxdeDJvEO0cOzJkrW4jiWByhibOO8tJCKegbkg5+riDiLAiCbnuxZUOqPnLQnBBQLxEYPDB5LwaB45DiejcUKOb4FGDrzkSJ5kBxRppAeXaafvs/gQep7VVwVy7e8T6HFO0haoiXsZp4d2gelpiTEpJrAlGvXJODDzMJPoEcpeHEDUUroH1+PXCGmZL8mB5a+ZzcP14IRsxWEygTy64MADa5RQ3U7qpSKSSiCRvTp1CUIMTEzgcYDziWCpWwdDEjrmyoQy3sUpdxwFrShQ0gwxgFgfawlR31d1rJxarF1/ZOsEa3RbbDdJWS4MwgMbYi70gB4UFTDLkCgYEA9bsfRblnK44C0oWTVxemxtuP96JPpqFj+jtcUMSBDZvnXyV5TKMWiP+agefWgQ5Gz5z6yBEicXvMcC9qcYf2nNnZYeTiCJmSof8dqWg5Uah3l+GBBJ13AVcrhJv/pm1Gkm3+WubREQBEXq3l9F/cRyEMzF2XWFCdrjX7R1JufssCgYEA6pTPTrIxufboxtJJXusdSSueqxN5see4TiqKXizRMuUaEF9h0iHd1fvxHWSMo3zlLt8s4LrR3PlKGXo88RnScNvRE3KyvznLkRhwdaFvTQjSUrMe+wV+OIRJm9UnV2ysqrB3w8+GP6iZPdiRN/AW4rkoPf0SMo2IGYR1/JsLlTMCgYBJxXqW+RlDFyg7wYRBYkVcb/AhvOXCtbMJHacSTFweFM76Xoqy+kc6q9nb5Bket4WEsLENPS+k+DChAWsoWFQuNKyxWgCN6mT+I1PpVvPWUwhMXZPZKdjfWycicZ7nfOjx7vmsmpzrSLQ95GEj41+DLyXjeLmF9vXPpj8g41tuzwKBgQCK31nzDs8ddqzLt4Y0KSCHRsmCId9zkOitbcXIhuO6K6NIeg8hJWd83NAbRIF17+SF4R1iVXcUSIizmIgne8/3fErEJqznREHdPgilutJ3WneY+e2nUdMthjNFi+TkfrOhwSLFyz+AxEEkOeeOpBYIVvEZ8Y4qW1ttL9vhlbA/vQKBgGrC0rchgbdL9Ehd8lG5yDYce1N2ZAxDLLGzyxbp76OExGQMj6vBJZeGp1S6ICNLSbbVWD3Wflk1d0o1o47GgF9p+PXJyeKes2ZTOByH0R+8M92fjVXmOxNUvC0oiqVTlFLd18cH4Yd9d6DaA+msmnkJY62tyZgceJcAmTwRVHkJ",
			//异步通知地址
			'notify_url' => "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/alipay_notify.html",
			//同步跳转
			'return_url' => "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html",
			//编码格式
			'charset' => "UTF-8",
			//签名方式
			'sign_type' => "RSA2",
			//支付宝网关
			'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
			//支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
			'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4SvhwaggPK6YcT9KFcWatlWzmPOGuinPibsSuQOKOzIdndmsobx8gxYsL40SBJZJ7gUzLW53WUPJiu1Cn2K6b1m/PsOQNl6WRQD7fD62fCO5z3Wqitx9bts/LoUbX7vb4Dxpplw7KKVikUCBwe75hOTuhAfQ7dqGzbE0xfKjO2ugRBDceCy5InBK/xfvVbNRk+1DZyexLSUJx7pm5nUCkVj81URlnQYzcW06OBjvSSecTpmAktbvruZE450vhxkfDzxp47R0qba4c8ALRrDlnrUb29EPD4TFmXWGxteZQBQWKbEJWte7tV/sGW9ed/6QeC8A9N3CalnzXpqIF4hpcQIDAQAB",
		);


		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $data['balance_sn'];

		//订单名称，必填
		$subject = '用户充值';

		//付款金额，必填
		$total_amount = $data['bpprice'];

		//商品描述，可空
		$body = '';

		//超时时间
		$timeout_express = "1m";

		$payRequestBuilder = new AlipayTradeWapPayContentBuilder();
		$payRequestBuilder->setBody($body);
		$payRequestBuilder->setSubject($subject);
		$payRequestBuilder->setOutTradeNo($out_trade_no);
		$payRequestBuilder->setTotalAmount($total_amount);
		$payRequestBuilder->setTimeExpress($timeout_express);

		$payResponse = new AlipayTradeService($config);

		$result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);

		return $result;
	}

	/**
	 * izpay
	 * @author lukui  2017-08-16
	 * @return [type] [description]
	 */
	public function izpay_wx($data) {

		header("Access-Control-Allow-Origin: *");

		$url = 'http://www.izpay.cn:9002/thirdsync_server/third_pay_server';

		$para['out_trade_no'] = $data['balance_sn'];
		$para['mer_id'] = 'pay177';
		$para['goods_name'] = 'userpay';
		$para['total_fee'] = $data['bpprice'] * 100;
		$para['callback_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html";
		$para['notify_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/izpay_wx_notify.html";

		$para['attach'] = '709';
		$para['nonce_str'] = mt_rand(time(), time() + rand());
		$para['pay_type'] = '003';
		$key = "c71elu2cq25b5m8ks99fxhqteljugo6m";




		$sign_str = 'mer_id=' . $para['mer_id'] . '&nonce_str=' . $para['nonce_str'] . '&out_trade_no=' . $para['out_trade_no'] . '&total_fee=' . $para['total_fee'] . '&key=' . $key;

		//echo $sign_str;

		$para['sign'] = md5($sign_str);


		$str = "";
		foreach ($para as $key => $val) {
			$str .= $key . '=' . $val . '&';
		}
		$newstr = substr($str, 0, strlen($str) - 1);

		$pay_url = $url . '?' . $newstr;


		$temp_data = file_get_contents($pay_url);
		$result = json_decode($temp_data, true);


		return $temp_data;
	}

	public function izpay_alipay($data) {

		header("Access-Control-Allow-Origin: *");

		$url = 'http://www.izpay.cn:9002/thirdsync_server/third_pay_server';

		$para['out_trade_no'] = $data['balance_sn'];
		$para['mer_id'] = 'pay177';
		$para['goods_name'] = 'userpay';
		$para['total_fee'] = $data['bpprice'] * 100;
		$para['callback_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html";
		$para['notify_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/izpay_wx_notify.html";

		$para['attach'] = '709';
		$para['nonce_str'] = mt_rand(time(), time() + rand());
		$para['pay_type'] = '006';
		$key = "c71elu2cq25b5m8ks99fxhqteljugo6m";




		$sign_str = 'mer_id=' . $para['mer_id'] . '&nonce_str=' . $para['nonce_str'] . '&out_trade_no=' . $para['out_trade_no'] . '&total_fee=' . $para['total_fee'] . '&key=' . $key;

		//echo $sign_str;

		$para['sign'] = md5($sign_str);


		$str = "";
		foreach ($para as $key => $val) {
			$str .= $key . '=' . $val . '&';
		}
		$newstr = substr($str, 0, strlen($str) - 1);

		$pay_url = $url . '?' . $newstr;


		$temp_data = file_get_contents($pay_url);
		$result = json_decode($temp_data, true);


		return $temp_data;
	}

	public function izpay_wx_notify() {
		$data = input('');
		if (!isset($data['out_trade_no'])) {
			return false;
		}
		$this->notify_ok_dopay($data['out_trade_no'], $data['total_fee'] / 100);
		return true;
	}

	/**
	 * 平安微信扫码支付
	 * @author lukui  2017-08-17
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function pingan_code($balance, $code) {
		$papay = new Webapp();

		$data['out_no'] = $balance['balance_sn'];
		$data['pmt_tag'] = $code;
		$data['original_amount'] = $balance['bpprice'] * 100;
		$data['trade_amount'] = $balance['bpprice'] * 100;
		$data['ord_name'] = 'userpay';
		$data['auth_code'] = "";
		$data['jump_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html";
		;
		$data['notify_url'] = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/panotify.html";
		;
		$result = $papay->api("payorder", $data);
		return $result;
	}

	public function panotify() {

		$data = $_REQUEST;

		if (isset($data['amount']) && isset($data['out_no'])) {
			$this->notify_ok_dopay($data['out_no'], $data['amount'] / 100);
		}
	}

	//钱通支付
	public function qiantong_pay($data) {
		$gateway_url = "https://123.56.119.177:8443/pay/pay.htm";

		$str = '<?xml version="1.0" encoding="utf-8" standalone="no"?>
                <message application="WeiXinScanOrder" version="1.0.1"
                    timestamp="20160210111111"
                    merchantId="1002207"
                    merchantOrderId="' . $data['balance_sn'] . '"
                    merchantOrderAmt="' . ($data['bpprice'] * 100) . '"
                    merchantOrderDesc="用户充值"
                    userName=""
                    payerId="' . $data['uid'] . '"
                    salerId=""
                    guaranteeAmt="0"
                    merchantPayNotifyUrl="' . "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/qiantong_notify.html" . '"/>';


		/*		 * ***生成请求内容**开始**** */
		$strMD5 = MD5($str, true);
		$strsign = $this->qt_sign($strMD5);
		$base64_src = base64_encode($str);
		$msg = $base64_src . "|" . $strsign;
		/*		 * ***生成请求内容**结束**** */
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $gateway_url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		$tmp = explode("|", $result);
		$resp_xml = base64_decode($tmp[0]);

		$resp_sign = $tmp[1];
		if ($this->qt_verity(MD5($resp_xml, true), $resp_sign) && $_SESSION['uid'] != 1017) {//验签
			$res_arr = xml_to_array($resp_xml);
			$res_arr = $res_arr['@attributes'];

			if (isset($res_arr['respCode']) && $res_arr['respCode'] == 000 && isset($res_arr['codeUrl'])) {
				return $res_arr['codeUrl'];
			}
		} else
			return WPreturn('渠道不可用', -1);
	}

	/**
	 * 签名  生成签名串  基于sha1withRSA
	 * @param string $data 签名前的字符串
	 * @return string 签名串
	 */
	public function qt_sign($data) {
		$certs = array();
		$_file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/weixin/qiantong/merchant_cert.pfx");

		openssl_pkcs12_read($_file, $certs, "11111111"); //其中password为你的证书密码
		if (!$certs)
			return;
		$signature = '';
		openssl_sign($data, $signature, $certs['pkey']);
		return base64_encode($signature);
	}

	/**
	 * 验证签名： 
	 * @param data：原文 
	 * @param signature：签名 
	 * @return bool 返回：签名结果，true为验签成功，false为验签失败 
	 */
	public function qt_verity($data, $signature) {
		$pubKey = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/weixin/qiantong/server_cert.cer");
		$res = openssl_get_publickey($pubKey);
		$result = (bool) openssl_verify($data, base64_decode($signature), $res);
		openssl_free_key($res);
		return $result;
	}

	public function qiantong_kuaijie($data) {
		$gateway_url = "https://123.56.119.177:8443/pay/pay.htm";

		$str = '<?xml version="1.0" encoding="utf-8" standalone="no"?>
        <message application="CertPayOrderH5" guaranteeAmt="0"
            merchantFrontEndUrl="http://' . $_SERVER['SERVER_NAME'] . '/index/user/index.html"
            merchantId="1002207" merchantName=""
            merchantOrderAmt="' . ($data['bpprice'] * 100) . '" merchantOrderDesc="用户充值" merchantOrderId="' . $data['balance_sn'] . '"
            merchantPayNotifyUrl="' . "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/qiantong_notify.html" . '"
            payerId="' . $data['uid'] . '" salerId="" version="1.0.1" />';




		/*		 * ***生成请求内容**开始**** */
		$strMD5 = MD5($str, true);
		$strsign = $this->qt_sign($strMD5);
		$base64_src = base64_encode($str);
		$msg = $base64_src . "|" . $strsign;

		/*		 * ***生成请求内容**结束**** */
		$def_url = '<form name="ipspay" action="' . $gateway_url . '" method="post">';
		$def_url .= '<input name="msg" type="text" value="' . $msg . '" />';
		$def_url .= '</form>';

		return $def_url;
	}

	public function qiantong_notify() {



		/*		 * ****异步通知***** */
		$result = file_get_contents('php://input', 'r');
		$tmp = explode("|", $result);
		$resp_xml = base64_decode($tmp[0]);

		$resp_sign = $tmp[1];
		if ($this->qt_verity(MD5($resp_xml, true), $resp_sign)) {//验签
			$resp_arr = xml_to_array($resp_xml);

			if (isset($resp_arr["deductList"]["item"]["@attributes"])) {
				$item = $resp_arr["deductList"]["item"]["@attributes"];
				$info = $resp_arr["@attributes"];
				if (isset($item["payStatus"]) && $item["payStatus"] == '01' && isset($info["merchantOrderId"]) && isset($item["payAmt"])) {
					$this->notify_ok_dopay($info["merchantOrderId"], round($item["payAmt"] / 100, 2));
				}
			}
		} else
			echo '验签失败';
	}

	public function wx_wap_2($data) {


		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);

		$ary = array(
			'token' => '670b4dc044bd939552228fe114e218b7', //填写用户TOKEN
			'mod' => 'pay', //模式,pay:支付模式,list:返回所有订单信息
			'index' => 1, //模式为list的时候使用,用来指定订单当前页,订单信息每页显示10条
			'oid' => $data['balance_sn'], //模式为list的时候使用,用来指定查询某个订单的信息
			'title' => '用户充值', //商品名称
			'price' => $data['bpprice'] * 100, //商品价格,请填写整数,以分为单位,例:1元,就填写100
			'curl' => "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/wxwap2n.html",
			'cip' => $_SERVER["REMOTE_ADDR"]//用户的支付IP,不可更改
		);

		$url = 'http://api.btjson.com/weixinpay';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ary));
		$content = curl_exec($ch);
		curl_close($ch);



		if ($ary['mod'] == 'pay') {
			$json = json_decode($content, true);
			$oid = $json['data']['oid']; //返回的订单号,可存在自己的数据库中
			$_data['bpid'] = $data['bpid'];
			$_data['pay_type'] = $oid;
			db('balance')->update($_data);
			if (iswechat()) {
				return $json['data']['h5url'];
			} else {
				return $json['data']['pcurl'];
			}
			/*
			  if($json['data']['img'] != ''){
			  header('Content-Type:image/png');
			  echo base64_decode($json['data']['img']);
			  }else{
			  echo $json['data'];
			  } */
		}
		if ($ary['mod'] == 'list') {
			return WPreturn('渠道不可用', -1);
		}
	}

	//易通支付
	public function etongConfig() {
		/*
		  $merchantId = "888888888888888"; //商户代码
		  $bussId = "100000"; //业务代码
		  $datakey = "tWmmy8AS1c691DgL"; //数据密钥
		  //http://58.56.23.89:7002/NetPay/BankSelect.action
		  $payUrl = "http://58.56.23.89:7002/NetPay/BankSelect.action"; //支付网关地址
		  //http://58.56.23.89:7002/NetPay/MerOrderQuery.action
		  $queryUrl = "http://192.168.10.36:7002/NetPay/MerOrderQuery.action"; //订单状态查询地址

		  $merchantId = "888201709220105"; //商户代码
		  $bussId = "881471"; //业务代码
		  $datakey = "tWmmy8AS1c691DgL"; //数据密钥
		  $payUrl = "http://cashier.etonepay.com/NetPay/BankSelect.action"; //支付网关地址
		  $queryUrl = "http://cashier.etonepay.com/NetPay/MerOrderQuery.action"; //订单状态查询地址
		  //$merUrl = "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html"; //页面返回地址
		  //$backUrl = "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/etone_notify.html"; //后台通知地址
		  $merUrl = "http://47.52.154.110/index/index/index.html"; //页面返回地址
		  $backUrl = "http://47.52.154.110/index/pay//etone_notify.html"; //后台通知地址
		 */
		return array(
			"merchantId" => "888201709220105",
			"bussId" => "881472", //881471PC网银 881472 手机快捷  881473手机扫码  881474PC扫码
			"datakey" => "tWmmy8AS1c691DgL",
			"payUrl" => "http://cashier.etonepay.com/NetPay/BankSelect.action",
			"queryUrl" => "http://cashier.etonepay.com/NetPay/MerOrderQuery.action",
			"merUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html",
			//"backUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/etone_notify.html",
			"backUrl" => "http://120.79.34.191/index/pay/etone_notify.html",
		);
	}

	public function etonepay($data) {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);

		$etongConfig = $this->etongConfig();

		$userId = $data['uid']; //易通支付会员ID代码，可为空
		$ary = array(
			'version' => "1.0.0", //版本号 默认填 1.0.0
			'transCode' => "8888", //交易代码  8888：普通支付 6666：担保支付
			'merchantId' => $etongConfig['merchantId'], //商户编号  由易通公司分配
			'merOrderNum' => $data['balance_sn'], //商户订单号  如：0000010000100000
			'bussId' => $etongConfig['bussId'], //业务代码  由易通公司分配
			'tranAmt' => $data['bpprice'] * 100, //交易金额(单位： 分)
			'sysTraceNum' => $data['balance_sn'], //商户请求流水号  如：0000010000100001
			'tranDateTime' => date("YmdHis"), //交易时间  YYYYMMDDHHMMSS
			'currencyType' => 156, //货币代码   人民币：156
			'merURL' => $etongConfig['merUrl'], //商户返回页面  页面返回地址
			'backURL' => $etongConfig['backUrl'], //回调商户地址  后台通知地址（为空时不通知）
			'orderInfo' => $this->strToHex("系统充值{$data['bpprice']}元"), //订单信息  值可以为空
			'userId' => "", //用户 ID  值必须为空
			'userIp' => "", //订单用户 IP 为空表示不验证
			'bankId' => "", //支付方式代码  选填（由一卡通分配）
			'stlmId' => "", //结算规则代码  值可以为空
			'entryType' => "", //入口类型  分为以下几种情况： 1. 值为1：支持易通虚拟账户和银行卡支付 2. 值为2：支持一卡通虚拟账户和一 卡通（鸿运卡、商务卡、通用卡） 支付 3. 值为3：支持一卡通（鸿运卡、商 务卡、通用卡）支付 4. 值为4：支持一卡通虚拟账户支付
			'reserver1' => "", //保留域 1
			'reserver2' => "", //保留域 2
			'reserver3' => "", //保留域 3
			'reserver4' => "", //保留域 4
			//'signValue' => $signValue,
		);
		$ary['signValue'] = md5($ary['version'] . "|" . $ary['transCode'] . "|" . $ary['merchantId'] . "|" . $ary['merOrderNum'] . "|" . $ary['bussId'] . "|" . $ary['tranAmt'] . "|" . $ary['sysTraceNum'] . "|" . $ary['tranDateTime'] . "|" . $ary['currencyType'] . "|" . $ary['merURL'] . "|" . $ary['backURL'] . "|" . $ary['orderInfo'] . "|" . $ary['userId'] . $etongConfig['datakey']);


		$def_url = '<form name="payForm" action="' . $etongConfig['payUrl'] . '" method="post" id="payForm">';
		foreach ($ary as $k => $v) {
			$def_url .= '<input name="' . $k . '" type="hidden" value="' . $v . '" />';
		}
		$def_url .= '</form>';
		return $def_url;
	}

	//易通支付回调,验签

	public function etone_notify() {
		$etongConfig = $this->etongConfig();
		$res = array(
			"transCode" => isset($_REQUEST['transCode']) ? $_REQUEST['transCode'] : "8888", //交易代码 填写：8888
			"merchantId" => isset($_REQUEST['merchantId']) ? $_REQUEST['merchantId'] : null, //$_REQUEST['merchantId'], //商户编号  由易通公司分配
			"respCode" => isset($_REQUEST['respCode']) ? $_REQUEST['respCode'] : null, //$_REQUEST['respCode'], //返回码  0000 为成功，9999 为失败
			"sysTraceNum" => isset($_REQUEST['sysTraceNum']) ? $_REQUEST['sysTraceNum'] : null, //$_REQUEST['sysTraceNum'], //商户请求流水号  同商户请求流水号
			"merOrderNum" => isset($_REQUEST['merOrderNum']) ? $_REQUEST['merOrderNum'] : null, //$_REQUEST['merOrderNum'], //商户订单号  如：0000010000100002
			"orderId" => isset($_REQUEST['orderId']) ? $_REQUEST['orderId'] : null, //$_REQUEST['orderId'], //支付网关订单号  如：00000100001000001234
			"bussId" => isset($_REQUEST['bussId']) ? $_REQUEST['bussId'] : null, //$_REQUEST['bussId'], //业务代码  由易通公司分配
			"tranAmt" => isset($_REQUEST['tranAmt']) ? $_REQUEST['tranAmt'] : null, //$_REQUEST['tranAmt'], //实际交易金额  精确到分，例如 198
			"orderAmt" => isset($_REQUEST['orderAmt']) ? $_REQUEST['orderAmt'] : null, //$_REQUEST['orderAmt'], //订单金额  精确到分，例如 100
			"bankFeeAmt" => isset($_REQUEST['bankFeeAmt']) ? $_REQUEST['bankFeeAmt'] : null, //$_REQUEST['bankFeeAmt'], //支付渠道手续费 精确到分，例如 98
			"integralAmt" => isset($_REQUEST['integralAmt']) ? $_REQUEST['integralAmt'] : null, //$_REQUEST['integralAmt'], //积分抵扣金额 精确到分，例如 1
			"vaAmt" => isset($_REQUEST['vaAmt']) ? $_REQUEST['vaAmt'] : null, //$_REQUEST['vaAmt'], //虚拟账户支付金额  精确到分，例如 0
			"bankAmt" => isset($_REQUEST['bankAmt']) ? $_REQUEST['bankAmt'] : null, //$_REQUEST['bankAmt'], //支付渠道支付金额 精确到分，例如 98
			"bankId" => isset($_REQUEST['bankId']) ? $_REQUEST['bankId'] : null, //$_REQUEST['bankId'], //支付渠道 ID 支付渠道 ID
			"integralSeq" => isset($_REQUEST['integralSeq']) ? $_REQUEST['integralSeq'] : null, //$_REQUEST['integralSeq'], //积分交易流水号  如：积分交易流水号
			"vaSeq" => isset($_REQUEST['vaSeq']) ? $_REQUEST['vaSeq'] : null, //$_REQUEST['vaSeq'], //虚拟账户交易流水号 如：虚拟账户交易流水号
			"bankSeq" => isset($_REQUEST['bankSeq']) ? $_REQUEST['bankSeq'] : null, //$_REQUEST['bankSeq'], //支付机构交易流水号 如：支付机构交易流水号
			"tranDateTime" => isset($_REQUEST['tranDateTime']) ? $_REQUEST['tranDateTime'] : null, //$_REQUEST['tranDateTime'], //交易时间 YYYYMMDDHHMMSS(商户订单提交时
			"payMentTime" => isset($_REQUEST['payMentTime']) ? $_REQUEST['payMentTime'] : null, //$_REQUEST['payMentTime'], //支付时间 YYYYMMDDHHMMSS(订单支付时间)
			"settleDate" => isset($_REQUEST['settleDate']) ? $_REQUEST['settleDate'] : null, //$_REQUEST['settleDate'], //清算日 YYYYMMDD
			"currencyType" => isset($_REQUEST['currencyType']) ? $_REQUEST['currencyType'] : null, //$_REQUEST['currencyType'], //货币代码 人民币：156
			"orderInfo" => isset($_REQUEST['orderInfo']) ? $_REQUEST['orderInfo'] : null, //$_REQUEST['orderInfo'], //订单信息 值可以为空
			"userId" => isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null, //$_REQUEST['userId'], //用户 ID 商户接入值必须为空“”
			"userIp" => isset($_REQUEST['userIp']) ? $_REQUEST['userIp'] : null, //$_REQUEST['userIp'], //支付用户 IP
			"reserver1" => isset($_REQUEST['reserver1']) ? $_REQUEST['reserver1'] : null, //$_REQUEST['reserver1'], //保留域 1
			"reserver2" => isset($_REQUEST['reserver2']) ? $_REQUEST['reserver2'] : null, //$_REQUEST['reserver2'], //保留域 2
			"reserver3" => isset($_REQUEST['reserver3']) ? $_REQUEST['reserver3'] : null, //$_REQUEST['reserver3'], //保留域 3
			"reserver4" => isset($_REQUEST['reserver4']) ? $_REQUEST['reserver4'] : null, //$_REQUEST['reserver4'], //保留域 4
			"signValue" => isset($_REQUEST['signValue']) ? $_REQUEST['signValue'] : null, //$_REQUEST['signValue'], //数字签名
		);
		$mySign = md5($res['transCode'] . "|" . $res['merchantId'] . "|" . $res['respCode'] . "|" . $res['sysTraceNum'] . "|" . $res['merOrderNum'] . "|" . $res['orderId'] . "|" . $res['bussId'] . "|" . $res['tranAmt'] . "|" . $res['orderAmt'] . "|" . $res['bankFeeAmt'] . "|" . $res['integralAmt'] . "|" . $res['vaAmt'] . "|" . $res['bankAmt'] . "|" . $res['bankId'] . "|" . $res['integralSeq'] . "|" . $res['vaSeq'] . "|" . $res['bankSeq'] . "|" . $res['tranDateTime'] . "|" . $res['payMentTime'] . "|" . $res['settleDate'] . "|" . $res['currencyType'] . "|" . $res['orderInfo'] . "|" . $res['userId'] . $etongConfig['datakey']);
		file_put_contents("etone_notify.log", var_export($_REQUEST, true), FILE_APPEND);
		file_put_contents("etone_notify.log", $mySign, FILE_APPEND);
		if ($mySign == $res['signValue']) {
			if ($res["respCode"] == "0000") {
				$this->notify_ok_dopay($res["merOrderNum"], round($res["orderAmt"] / 100, 2));
			}
			return 'success';
		} else {
			return "签名验证失败！";
		}
	}

	//易通支付2
	public function etongConfig2() {
		return array(
			"merchantId" => "888201707220102",
			"bussId" => "888341", //881471PC网银 881472 手机快捷  881473手机扫码  881474PC扫码
			"datakey" => "85POzI9389z29H8R",
			"payUrl" => "http://cashier.etonepay.com/NetPay/BankSelect.action",
			"queryUrl" => "http://cashier.etonepay.com/NetPay/MerOrderQuery.action",
			"merUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html",
			//"backUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/etone_notify2.html",
			"backUrl" => "http://120.79.34.191/index/pay/etone_notify2.html",
		);
	}

	public function etonepay2($data) {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);

		$etongConfig = $this->etongConfig2();

		$userId = $data['uid']; //易通支付会员ID代码，可为空
		$ary = array(
			'version' => "1.0.0", //版本号 默认填 1.0.0
			'transCode' => "8888", //交易代码  8888：普通支付 6666：担保支付
			'merchantId' => $etongConfig['merchantId'], //商户编号  由易通公司分配
			'merOrderNum' => $data['balance_sn'], //商户订单号  如：0000010000100000
			'bussId' => $etongConfig['bussId'], //业务代码  由易通公司分配
			'tranAmt' => $data['bpprice'] * 100, //交易金额(单位： 分)
			'sysTraceNum' => $data['balance_sn'], //商户请求流水号  如：0000010000100001
			'tranDateTime' => date("YmdHis"), //交易时间  YYYYMMDDHHMMSS
			'currencyType' => 156, //货币代码   人民币：156
			'merURL' => $etongConfig['merUrl'], //商户返回页面  页面返回地址
			'backURL' => $etongConfig['backUrl'], //回调商户地址  后台通知地址（为空时不通知）
			'orderInfo' => $this->strToHex("系统充值{$data['bpprice']}元"), //订单信息  值可以为空
			'userId' => "", //用户 ID  值必须为空
			'userIp' => "", //订单用户 IP 为空表示不验证
			'bankId' => "", //支付方式代码  选填（由一卡通分配）
			'stlmId' => "", //结算规则代码  值可以为空
			'entryType' => "", //入口类型  分为以下几种情况： 1. 值为1：支持易通虚拟账户和银行卡支付 2. 值为2：支持一卡通虚拟账户和一 卡通（鸿运卡、商务卡、通用卡） 支付 3. 值为3：支持一卡通（鸿运卡、商 务卡、通用卡）支付 4. 值为4：支持一卡通虚拟账户支付
			'reserver1' => "", //保留域 1
			'reserver2' => "", //保留域 2
			'reserver3' => "", //保留域 3
			'reserver4' => "", //保留域 4
			//'signValue' => $signValue,
		);
		$ary['signValue'] = md5($ary['version'] . "|" . $ary['transCode'] . "|" . $ary['merchantId'] . "|" . $ary['merOrderNum'] . "|" . $ary['bussId'] . "|" . $ary['tranAmt'] . "|" . $ary['sysTraceNum'] . "|" . $ary['tranDateTime'] . "|" . $ary['currencyType'] . "|" . $ary['merURL'] . "|" . $ary['backURL'] . "|" . $ary['orderInfo'] . "|" . $ary['userId'] . $etongConfig['datakey']);


		$def_url = '<form name="payForm" action="' . $etongConfig['payUrl'] . '" method="post" id="payForm">';
		foreach ($ary as $k => $v) {
			$def_url .= '<input name="' . $k . '" type="hidden" value="' . $v . '" />';
		}
		$def_url .= '</form>';
		return $def_url;
	}

	//易通支付回调,验签
	public function etone_notify2() {
		$etongConfig = $this->etongConfig2();
		$res = array(
			"transCode" => isset($_REQUEST['transCode']) ? $_REQUEST['transCode'] : "8888", //交易代码 填写：8888
			"merchantId" => isset($_REQUEST['merchantId']) ? $_REQUEST['merchantId'] : null, //$_REQUEST['merchantId'], //商户编号  由易通公司分配
			"respCode" => isset($_REQUEST['respCode']) ? $_REQUEST['respCode'] : null, //$_REQUEST['respCode'], //返回码  0000 为成功，9999 为失败
			"sysTraceNum" => isset($_REQUEST['sysTraceNum']) ? $_REQUEST['sysTraceNum'] : null, //$_REQUEST['sysTraceNum'], //商户请求流水号  同商户请求流水号
			"merOrderNum" => isset($_REQUEST['merOrderNum']) ? $_REQUEST['merOrderNum'] : null, //$_REQUEST['merOrderNum'], //商户订单号  如：0000010000100002
			"orderId" => isset($_REQUEST['orderId']) ? $_REQUEST['orderId'] : null, //$_REQUEST['orderId'], //支付网关订单号  如：00000100001000001234
			"bussId" => isset($_REQUEST['bussId']) ? $_REQUEST['bussId'] : null, //$_REQUEST['bussId'], //业务代码  由易通公司分配
			"tranAmt" => isset($_REQUEST['tranAmt']) ? $_REQUEST['tranAmt'] : null, //$_REQUEST['tranAmt'], //实际交易金额  精确到分，例如 198
			"orderAmt" => isset($_REQUEST['orderAmt']) ? $_REQUEST['orderAmt'] : null, //$_REQUEST['orderAmt'], //订单金额  精确到分，例如 100
			"bankFeeAmt" => isset($_REQUEST['bankFeeAmt']) ? $_REQUEST['bankFeeAmt'] : null, //$_REQUEST['bankFeeAmt'], //支付渠道手续费 精确到分，例如 98
			"integralAmt" => isset($_REQUEST['integralAmt']) ? $_REQUEST['integralAmt'] : null, //$_REQUEST['integralAmt'], //积分抵扣金额 精确到分，例如 1
			"vaAmt" => isset($_REQUEST['vaAmt']) ? $_REQUEST['vaAmt'] : null, //$_REQUEST['vaAmt'], //虚拟账户支付金额  精确到分，例如 0
			"bankAmt" => isset($_REQUEST['bankAmt']) ? $_REQUEST['bankAmt'] : null, //$_REQUEST['bankAmt'], //支付渠道支付金额 精确到分，例如 98
			"bankId" => isset($_REQUEST['bankId']) ? $_REQUEST['bankId'] : null, //$_REQUEST['bankId'], //支付渠道 ID 支付渠道 ID
			"integralSeq" => isset($_REQUEST['integralSeq']) ? $_REQUEST['integralSeq'] : null, //$_REQUEST['integralSeq'], //积分交易流水号  如：积分交易流水号
			"vaSeq" => isset($_REQUEST['vaSeq']) ? $_REQUEST['vaSeq'] : null, //$_REQUEST['vaSeq'], //虚拟账户交易流水号 如：虚拟账户交易流水号
			"bankSeq" => isset($_REQUEST['bankSeq']) ? $_REQUEST['bankSeq'] : null, //$_REQUEST['bankSeq'], //支付机构交易流水号 如：支付机构交易流水号
			"tranDateTime" => isset($_REQUEST['tranDateTime']) ? $_REQUEST['tranDateTime'] : null, //$_REQUEST['tranDateTime'], //交易时间 YYYYMMDDHHMMSS(商户订单提交时
			"payMentTime" => isset($_REQUEST['payMentTime']) ? $_REQUEST['payMentTime'] : null, //$_REQUEST['payMentTime'], //支付时间 YYYYMMDDHHMMSS(订单支付时间)
			"settleDate" => isset($_REQUEST['settleDate']) ? $_REQUEST['settleDate'] : null, //$_REQUEST['settleDate'], //清算日 YYYYMMDD
			"currencyType" => isset($_REQUEST['currencyType']) ? $_REQUEST['currencyType'] : null, //$_REQUEST['currencyType'], //货币代码 人民币：156
			"orderInfo" => isset($_REQUEST['orderInfo']) ? $_REQUEST['orderInfo'] : null, //$_REQUEST['orderInfo'], //订单信息 值可以为空
			"userId" => isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null, //$_REQUEST['userId'], //用户 ID 商户接入值必须为空“”
			"userIp" => isset($_REQUEST['userIp']) ? $_REQUEST['userIp'] : null, //$_REQUEST['userIp'], //支付用户 IP
			"reserver1" => isset($_REQUEST['reserver1']) ? $_REQUEST['reserver1'] : null, //$_REQUEST['reserver1'], //保留域 1
			"reserver2" => isset($_REQUEST['reserver2']) ? $_REQUEST['reserver2'] : null, //$_REQUEST['reserver2'], //保留域 2
			"reserver3" => isset($_REQUEST['reserver3']) ? $_REQUEST['reserver3'] : null, //$_REQUEST['reserver3'], //保留域 3
			"reserver4" => isset($_REQUEST['reserver4']) ? $_REQUEST['reserver4'] : null, //$_REQUEST['reserver4'], //保留域 4
			"signValue" => isset($_REQUEST['signValue']) ? $_REQUEST['signValue'] : null, //$_REQUEST['signValue'], //数字签名
		);
		$mySign = md5($res['transCode'] . "|" . $res['merchantId'] . "|" . $res['respCode'] . "|" . $res['sysTraceNum'] . "|" . $res['merOrderNum'] . "|" . $res['orderId'] . "|" . $res['bussId'] . "|" . $res['tranAmt'] . "|" . $res['orderAmt'] . "|" . $res['bankFeeAmt'] . "|" . $res['integralAmt'] . "|" . $res['vaAmt'] . "|" . $res['bankAmt'] . "|" . $res['bankId'] . "|" . $res['integralSeq'] . "|" . $res['vaSeq'] . "|" . $res['bankSeq'] . "|" . $res['tranDateTime'] . "|" . $res['payMentTime'] . "|" . $res['settleDate'] . "|" . $res['currencyType'] . "|" . $res['orderInfo'] . "|" . $res['userId'] . $etongConfig['datakey']);
		file_put_contents("etone_notify2.log", var_export($_REQUEST, true), FILE_APPEND);
		file_put_contents("etone_notify2.log", $mySign, FILE_APPEND);
		if ($mySign == $res['signValue']) {
			if ($res["respCode"] == "0000") {
				$this->notify_ok_dopay($res["merOrderNum"], round($res["orderAmt"] / 100, 2));
			}
			return 'success';
		} else {
			return "签名验证失败！";
		}
	}

//16进制ascii码转字符串
	public function hexToStr($hex) {
		$string = '';
		for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
			$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
		}
		return $string;
	}

	//字符串转16进制ascii码
	public function strToHex($string) {
		$hex = '';
		for ($i = 0; $i < strlen($string); $i++) {
			$hex .= dechex(ord($string[$i]));
		}
		return strtoupper($hex);
	}

	/* 聚合支付部分 */

//name:juhepay_wx_qrcode|title:微信扫码支付
	public function juhepay($data, $type) {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		$juheConfig = $this->juheConfig();

		//'http://auth.coincard.cc/pay/openId/6?returl= '+encodeURIComponent(location.href);

		$juhePay = array(
			"TradeType" => "bis.pay.submit", //交易类型  bis.pay.submit
			"OperatorID" => $juheConfig['MerchantID'], //操作员  默认商户编号
			"PayType" => $type, /* 0203-微信扫码支付；0204-支付宝扫码支付；0205-微信app支付；0207-微信公众号支付 */
			"TerminalType" => $this->get_device_type(), //终端类型  Android、IOS、PC、Others
			"MerchantID" => $juheConfig['MerchantID'], //商户编号
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid  微信公众号支付时必填
			"BankID" => "", //银行代码  网银支付必填（网银支付银行代码见附录）
			"OrderID" => $data['balance_sn'], //订单号
			//"DeviceID" => "1001", //设备号
			"Subject" => "系统充值{$data['bpprice']}元", //商品名称
			"MachineIP" => $this->getClientIp(), //终端IP  订单生成的机器IP
			"NotifyUrl" => $juheConfig['NotifyUrl'], //通知地址
			"ReturnUrl" => $juheConfig['ReturnUrl'], //返回地址
			"SubmitTime" => date("YmdHis"), //订单提交时间  格式：yyyyMMddHHmmss
			"OrderValidity" => date("YmdHis", time() + 60 * 10), //订单有效截止时间  格式：yyyyMMddHHmmss
			"CreditLimit" => "0", //信用卡限制使用标识   1表示限制使用信用卡，0或者其他标识不限制
			"Amt" => $data['bpprice'] * 100, //交易金额  单位为分，不含小数点
			"Summary" => $juheConfig['KeyNum'], //交易附言
		);
		$juhePay = $this->paraFilter($juhePay);
		$juhePay['Sign'] = $this->juheSign($juhePay, $juheConfig['md5Key']);
		$Reply = $this->curlPost($juheConfig['payUrl'], $juhePay);
		//var_export($Rep$Replyly);
		$result = array();
		parse_str($Reply, $result);
		return $result;
		//return $this->juheSignVerify($result, $juheConfig['md5Key']);
		/*
		  if ($this->juheSignVerify($result, $juheConfig['md5Key'])) {
		  return $result;
		  } else {
		  return array("RetStatus" => "9999", "RetMsg" => "接口调用失败或签名验证失败！","RetDesc" => "接口调用失败或签名验证失败！");
		  } */

		//return $Reply . var_export($juhePay, true);
	}

	public function juhepay_yinlian($data) {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		$juheConfig = $this->juheConfig_yinlian();

		//'http://auth.coincard.cc/pay/openId/6?returl= '+encodeURIComponent(location.href);
		$juhePay = array(
			"TradeType" => "bis.pay.submit", //交易类型  bis.pay.submit
			"OperatorID" => $juheConfig['MerchantID'], //操作员  默认商户编号
			"PayType" => "0208", /* 0203-微信扫码支付；0204-支付宝扫码支付；0205-微信app支付；0207-微信公众号支付 */
			"TerminalType" => $this->get_device_type(), //终端类型  Android、IOS、PC、Others
			"MerchantID" => $juheConfig['MerchantID'], //商户编号
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid  微信公众号支付时必填
			"BankID" => "", //银行代码  网银支付必填（网银支付银行代码见附录）
			"OrderID" => $data['balance_sn'], //订单号
			//"DeviceID" => "1001", //设备号
			"Subject" => "系统充值{$data['bpprice']}元", //商品名称
			"MachineIP" => $this->getClientIp(), //终端IP  订单生成的机器IP
			"NotifyUrl" => $juheConfig['NotifyUrl'], //通知地址
			"ReturnUrl" => $juheConfig['ReturnUrl'], //返回地址
			"SubmitTime" => date("YmdHis"), //订单提交时间  格式：yyyyMMddHHmmss
			"OrderValidity" => date("YmdHis", time() + 60 * 10), //订单有效截止时间  格式：yyyyMMddHHmmss
			"CreditLimit" => "0", //信用卡限制使用标识   1表示限制使用信用卡，0或者其他标识不限制
			"Amt" => $data['bpprice'] * 100, //交易金额  单位为分，不含小数点
			"Summary" => $juheConfig['KeyNum'], //交易附言
		);
		$juhePay = $this->paraFilter($juhePay);
		$juhePay['Sign'] = $this->juheSign($juhePay, $juheConfig['md5Key']);
		$payform = '<form name="payForm" action="' . $juheConfig['payUrl'] . '" method="post" id="payForm">';
		foreach ($juhePay as $k => $v) {
			$payform .= '<input name="' . $k . '" type="hidden" value="' . $v . '" />';
		}
		$payform .= '</form>';
		return $payform;
	}

	public function juheSign($data, $md5Key) {
		ksort($data);
		reset($data);
		$signString = "";
		foreach ($data as $k => $v) {
			if ($v !== "") {
				$signString .= "{$k}={$v}&";
			}
		}
		return strtoupper(md5($signString . "Key={$md5Key}"));
	}

	public function juheSignVerify($data, $md5Key) {
		$sign = $data['Sign'];
		$data = $this->paraFilter($data);
		$mysgin = $this->juheSign($data, $md5Key);
		if ($mysgin == $sign) {
			return true;
		} else {
			return false;
		}
	}

	public function juheConfig($k = null) {
		$config = array(
			array(
				"MerchantID" => "MD201710200000000503", //商户编号
				"md5Key" => "27PxJ7xOXUQbmTzQE4Ozfbax6COXyEsh", //md5密钥
			),
			array(
				"MerchantID" => "MD201710200000000504", //商户编号
				"md5Key" => "ZOo2XGviYoLihcqIvVeAaOOMDrqcD2TZ", //md5密钥
			),
			array(
				"MerchantID" => "MD201710200000000505", //商户编号
				"md5Key" => "LPC10GVn0bvuyId1i61gmzflcNWmTZ1R", //md5密钥
			),
		);
		if ($k === null) {
			$k = rand(0, count($config) - 1);
		}
		return array(
			"KeyNum" => $k, //md5密钥
			"MerchantID" => $config[$k]["MerchantID"], //商户编号
			"md5Key" => $config[$k]["md5Key"], //md5密钥
			"payUrl" => "http://pay.bisrec.com/aggpay/gateway/api/pay", //post提交接口
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid
			//"NotifyUrl" => "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/juhenotify.html", //异步通知地址
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/juhenotify.html", //异步通知地址
			//"ReturnUrl" => "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html", //同步返回地址
			"ReturnUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步返回地址
		);
	}

	public function juheConfig_yinlian() {
		return array(
			"KeyNum" => "-1", //md5密钥
			"MerchantID" => "MD201710200000001136", //商户编号
			"md5Key" => "rU7eLccS523K2TVDMNIQR0SxAArvgvsh", //md5密钥
			"payUrl" => "http://www.bisrec.com/aggpay/gateway/api/pay", //post提交接口
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid
			//"NotifyUrl" => "http://" . $_SERVER['SERVER_NAME'] . "/index/pay/juhenotify.html", //异步通知地址
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/juhenotify.html", //异步通知地址
			//"ReturnUrl" => "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html", //同步返回地址
			"ReturnUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步返回地址
		);
	}

	public function curlPost($url, $data) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}

	public function juhenotify() {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		if ($_POST['Summary'] == "-1") {
			$juheConfig = $this->juheConfig_yinlian();
		} else {
			$juheConfig = $this->juheConfig(intval($_POST['Summary']));
		}

		file_put_contents("juhepay.log", date("Y-m-d H:i:s") . var_export($_POST, true) . "\r\n", FILE_APPEND);
		if ($this->juheSignVerify($_POST, $juheConfig['md5Key'])) {
			$notifyArray = array(// 返回字段
				"RetStatus" => $_POST["RetStatus"], // 返回状态  //0表示成功非0表示失败此字段是通信标识，非交易标识，交易是否成功需要查看 DealStatus 来判断
				"RetDesc" => $_POST["RetDesc"], // 状态描述
				"DealStatus" => $_POST["DealStatus"], // 交易状态  //0已支付，1未支付，其他失败
				"RetCode" => $_POST["RetCode"], // 返回码
				"RetMsg" => $_POST["RetMsg"], //描述
				"Sign" => $_POST["Sign"], //签名,详见数据签名说明
				"PayType" => $_POST["PayType"], //支付类型  0203-微信扫码支付;0204-支付宝扫码支付;0205-微信app支付;0207-微信公众号支付
				"MerchantID" => $_POST["MerchantID"], //商户编号
				"OrderID" => $_POST["OrderID"], //订单号
				"Subject" => $_POST["Subject"], //商品名称
				"TradeTime" => $_POST["TradeTime"], //订单交易时间  格式：yyyyMMddHHmmss
				"Amt" => $_POST["Amt"], //交易金额  单位为分，不含小数点
				"Summary" => $_POST["Summary"], //交易附言
				"Status" => $_POST["Status"], //订单状态  01：未支付 ；02：已支付；03：已关闭；04：支付失败；05：订单超时；
			);
			if ($_POST['RetCode'] == '0000') {
				$this->notify_ok_dopay($notifyArray["OrderID"], round($notifyArray["Amt"] / 100, 2));
			}
			file_put_contents("juhepay.log", "SUCCESS\r\n\r\n", FILE_APPEND);
			echo "SUCCESS";
		} else {
			file_put_contents("juhepay.log", "验签失败\r\n\r\n", FILE_APPEND);
			echo "验签失败";
		}



		/*

		  if ($this->qt_verity(MD5($resp_xml, true), $resp_sign)) {//验签
		  $resp_arr = xml_to_array($resp_xml);
		  if (isset($resp_arr["deductList"]["item"]["@attributes"])) {
		  $item = $resp_arr["deductList"]["item"]["@attributes"];
		  $info = $resp_arr["@attributes"];
		  if (isset($item["payStatus"]) && $item["payStatus"] == '01' && isset($info["merchantOrderId"]) && isset($item["payAmt"])) {
		  $this->notify_ok_dopay($info["merchantOrderId"], round($item["payAmt"] / 100, 2));
		  }
		  }
		  } else
		  echo '验签失败';

		 */
	}

	public function juhereturn() {
		echo "hello";
	}

	public function paraFilter($para) {
		$para_filter = array();
		while (list ($key, $val) = each($para)) {
			if ($key == "Sign" || $key == "sign_type" || $val == "")
				continue;
			else
				$para_filter[$key] = $para[$key];
		}
		return $para_filter;
	}

	/* 聚合支付结束 */

	public function notify_ok_dopay($order_no, $order_amount) {

		if (!$order_no || !$order_amount) {

			return false;
		}

		$balance = db('balance')->where('balance_sn', $order_no)->find();
		if (!$balance) {

			return false;
		}

		if ($balance['bpprice'] != $order_amount) {

			return false;
		}

		if ($balance['bptype'] != 3) {

			return true;
		}
		$_edit['bpid'] = $balance['bpid'];
		$_edit['bptype'] = 1;
		$_edit['isverified'] = 1;
		$_edit['cltime'] = time();
		$_edit['bpbalance'] = $balance['bpbalance'] + $balance['bpprice'];

		$is_edit = db('balance')->update($_edit);

		if ($is_edit) {
			// add money
			$_ids = db('userinfo')->where('uid', $balance['uid'])->setInc('usermoney', $balance['bpprice']);
			if ($_ids) {
				//资金日志
				set_price_log($balance['uid'], 1, $balance['bpprice'], '充值', '用户充值', $_edit['bpid'], $_edit['bpbalance']);
			}

			return true;
		} else {

			return false;
		}
	}

	public function test_not() {

		dump(cache('padata'));
	}

	public function get_device_type() {
		//全部变成小写字母
		$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
		$type = 'Others';
		//分别进行判断
		if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
			$type = 'IOS';
		}

		if (strpos($agent, 'android')) {
			$type = 'Android';
		}
		return $type;
	}

	/*	 * ************************************************************
	 * 威富通支付接口
	 * 	 * ******************************************************* */

	public function swiftpass_weixin($data) {
		$notify_url = "http://{$_SERVER['HTTP_HOST']}/index/pay/swiftpass_callback.html";
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		require(__DIR__ . '/../../../pay/payInterface_native/Utils.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/config/config.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/RequestHandler.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/ClientResponseHandler.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/PayHttpClient.class.php');


		//初始化
		$this->resHandler = new \ClientResponseHandler();
		$this->reqHandler = new \RequestHandler();
		$this->pay = new \PayHttpClient();
		$this->cfg = new \Config();

		$this->reqHandler->setGateUrl($this->cfg->C('url'));
		$this->reqHandler->setKey($this->cfg->C('key'));



		/*
		  'version' => "1.0.0", //版本号 默认填 1.0.0
		  'transCode' => "8888", //交易代码  8888：普通支付 6666：担保支付
		  'merchantId' => $etongConfig['merchantId'], //商户编号  由易通公司分配
		  'merOrderNum' => $data['balance_sn'], //商户订单号  如：0000010000100000
		  'bussId' => $etongConfig['bussId'], //业务代码  由易通公司分配
		  'tranAmt' => $data['bpprice'] * 100, //交易金额(单位： 分)
		  'sysTraceNum' => $data['balance_sn'], //商户请求流水号  如：0000010000100001
		  'tranDateTime' => date("YmdHis"), //交易时间  YYYYMMDDHHMMSS
		  'currencyType' => 156, //货币代码   人民币：156
		  'merURL' => $etongConfig['merUrl'], //商户返回页面  页面返回地址
		  'backURL' => $etongConfig['backUrl'], //回调商户地址  后台通知地址（为空时不通知）
		  'orderInfo' => $this->strToHex("系统充值{$data['bpprice']}元"), //订单信息  值可以为空
		  'userId' => "", //用户 ID  值必须为空
		  'userIp' => "", //订单用户 IP 为空表示不验证
		  'bankId' => "", //支付方式代码  选填（由一卡通分配）
		  'stlmId' => "", //结算规则代码  值可以为空
		  'entryType' => "", //入口类型  分为以下几种情况： 1. 值为1：支持易通虚拟账户和银行卡支付 2. 值为2：支持一卡通虚拟账户和一 卡通（鸿运卡、商务卡、通用卡） 支付 3. 值为3：支持一卡通（鸿运卡、商 务卡、通用卡）支付 4. 值为4：支持一卡通虚拟账户支付
		 * 
		 * 		 */


		$this->reqHandler->setReqParams($_POST, array('method'));
		$this->reqHandler->setParameter('service', 'pay.weixin.native'); //接口类型
		$this->reqHandler->setParameter('mch_id', $this->cfg->C('mchId')); //必填项，商户号，由平台分配
		$this->reqHandler->setParameter('version', $this->cfg->C('version'));

		//$this->reqHandler->setParameter('op_shop_id', '1314');
		//$this->reqHandler->setParameter('device_info', '长江');
		$this->reqHandler->setParameter('body', '用户充值');
		$this->reqHandler->setParameter('mch_create_ip', $this->getClientIp());
		$this->reqHandler->setParameter('out_trade_no', $data['balance_sn']);

		//$this->reqHandler->setParameter('op_device_id', '东风一号');
		$this->reqHandler->setParameter('limit_credit_pay', '1');
		$this->reqHandler->setParameter('total_fee', $data['bpprice'] * 100);
		//this->reqHandler->setParameter('goods_tag','1fds');
		//$this->reqHandler->setParameter('groupno','8111100093');
		//通知地址，必填项，接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp
		//$notify_url = 'http://'.$_SERVER['HTTP_HOST'];
		//$this->reqHandler->setParameter('notify_url',$notify_url.'/payInterface/request.php?method=callback');
		$this->reqHandler->setParameter('notify_url', $notify_url);
		$this->reqHandler->setParameter('nonce_str', $data['balance_sn']); //随机字符串，必填项，不长于 32 位
		$this->reqHandler->createSign(); //创建签名

		$data = \Utils::toXml($this->reqHandler->getAllParameters());
		//var_dump($data);

		$this->pay->setReqContent($this->reqHandler->getGateURL(), $data);
		if ($this->pay->call()) {
			$this->resHandler->setContent($this->pay->getResContent());
			$this->resHandler->setKey($this->reqHandler->getKey());
			if ($this->resHandler->isTenpaySign()) {
				//当返回状态与业务结果都为0时才返回支付二维码，其它结果请查看接口文档
				if ($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0) {
					/*
					  echo json_encode(array('code_img_url' => $this->resHandler->getParameter('code_img_url'),
					  'code_url' => $this->resHandler->getParameter('code_url'),
					  'code_status' => $this->resHandler->getParameter('code_status')));
					 */
					return array(
						'status' => 0,
						'code_img_url' => $this->resHandler->getParameter('code_img_url'),
						'code_url' => $this->resHandler->getParameter('code_url'),
						'code_status' => $this->resHandler->getParameter('code_status'));

					//exit();
				} else {
					//echo json_encode(array('status' => 500, 'msg' => 'Error Code:' . $this->resHandler->getParameter('err_code') . ' Error Message:' . $this->resHandler->getParameter('err_msg')));
					return array('status' => 500, 'msg' => 'Error Code:' . $this->resHandler->getParameter('err_code') . ' Error Message:' . $this->resHandler->getParameter('err_msg'));
					//exit();
				}
			}
			//echo json_encode(array('status' => 500, 'msg' => 'Error Code:' . $this->resHandler->getParameter('status') . ' Error Message:' . $this->resHandler->getParameter('message')));
			return array('status' => 500, 'msg' => 'Error Code:' . $this->resHandler->getParameter('status') . ' Error Message:' . $this->resHandler->getParameter('message'));
		} else {
			//echo json_encode(array('status' => 500, 'msg' => 'Response Code:' . $this->pay->getResponseCode() . ' Error Info:' . $this->pay->getErrInfo()));
			return array('status' => 500, 'msg' => 'Response Code:' . $this->pay->getResponseCode() . ' Error Info:' . $this->pay->getErrInfo());
		}
	}

	public function swiftpass_callback() {
		$xml = file_get_contents('php://input');

		//file_put_contents('swiftpass_callback.log', $xml); //检测是否执行callback方法，如果执行，会生成1.txt文件，且文件中的内容就是通知参数
		file_put_contents("swiftpass_callback.log", $xml, FILE_APPEND);

		require(__DIR__ . '/../../../pay/payInterface_native/Utils.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/config/config.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/RequestHandler.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/ClientResponseHandler.class.php');
		require(__DIR__ . '/../../../pay/payInterface_native/class/PayHttpClient.class.php');


		//初始化
		$this->resHandler = new \ClientResponseHandler();
		$this->reqHandler = new \RequestHandler();
		$this->pay = new \PayHttpClient();
		$this->cfg = new \Config();

		$this->reqHandler->setGateUrl($this->cfg->C('url'));
		$this->reqHandler->setKey($this->cfg->C('key'));
		/*		 * ***************************************************** */

		$this->resHandler->setContent($xml);

		$this->resHandler->setKey($this->cfg->C('key'));
		if ($this->resHandler->isTenpaySign()) {

			if ($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0) {
				//echo $this->resHandler->getParameter('status');
				// 11;
				//校验单号和金额是否一致，更改订单状态等业务处理
				//if ($_POST['RetCode'] == '0000') {
				$OrderID = $this->resHandler->getParameter('out_trade_no');
				$Amt = $this->resHandler->getParameter('total_fee');
				$Amt = round($Amt / 100, 2);
				//$this->notify_ok_dopay($notifyArray["OrderID"], round($notifyArray["Amt"] / 100, 2));
				$this->notify_ok_dopay($OrderID, $Amt);
				//}


				\Utils::dataRecodes('接口回调收到通知参数', $this->resHandler->getAllParameters());
				echo 'success';
				//file_put_contents('2.txt', 1); //如果生成2.txt,说明前一步的输出success是有执行
				exit();
			} else {
				echo 'failure1';
				exit();
			}
		} else {
			echo 'failure2';
		}
	}

	/*	 * ********************************************************* */

	public function sandpay_qr($data, $type) {
		require(__DIR__ . '/../../../pay/sandpay/common.php');
		date_default_timezone_set("Asia/Shanghai");

		switch ($type) {
			case "0401":
				$productId = "00000006";
				break;
			case "0402":
				$productId = "00000005";
				break;
			case "0403":
				$productId = "00000007";
				break;
		}

		$prikey = loadPk12Cert(PRI_KEY_PATH, CERT_PWD);
		$pubkey = loadX509Cert(PUB_KEY_PATH);
		//$mid = '11050857';//商户号
		$postData = array(
			'head' => array(
				'version' => '1.0',
				'method' => 'sandpay.trade.precreate',
				'productId' => $productId, //微信：00000005  支付宝：00000006
				'accessType' => '1',
				'mid' => SAND_MID,
				'channelType' => '07',
				'reqTime' => date('YmdHis', time())
			),
			'body' => array(
				'payTool' => $type, ////0401：支付宝扫码  0402：微信扫码   0403：银联扫码
				'orderCode' => $data['balance_sn'], //订单编号
				'limitPay' => '1',
				'totalAmount' => str_pad($data['bpprice'] * 100, 12, "0", STR_PAD_LEFT),
				//'totalAmount' => '000000000001',
				'subject' => '充值',
				'body' => '账户充值',
				'txnTimeOut' => '20201230000000',
				'notifyUrl' => "http://120.76.67.199/index/pay/sandpay_callback.html",
				'extend' => ''
			)
		);
		$sign = sign($postData, $prikey);
		$post = array(
			'charset' => 'utf-8',
			'signType' => '01',
			'data' => json_encode($postData),
			'sign' => $sign
		);
		$result = http_post_json(API_HOST . '/order/create', $post);
		file_put_contents("sandpay_qr.log", var_export($postData, true) . "\r\n", FILE_APPEND);
		file_put_contents("sandpay_qr.log", var_export($result, true) . "\r\n", FILE_APPEND);
		parse_str(urldecode($result), $arr);
		$resp = json_decode($arr['data'], true);
		file_put_contents("sandpay_qr.log", var_export($resp, true) . "\r\n", FILE_APPEND);
		if ($resp['head']['respCode'] == "000000") {
			return array(
				'status' => 0,
				'code_img_url' => $resp['body']['qrCode'],
				'code_url' => $resp['body']['qrCode'],
				'code_status' => $resp['head']['respCode']
			);
		} else {
			return array('status' => 500, 'msg' => $resp['head']['respMsg']);
		}


		//return $arr['data'];
		//print_r($arr['data']);
	}

	public function sandpay_callback() {
		require(__DIR__ . '/../../../pay/sandpay/common.php');
		date_default_timezone_set("Asia/Shanghai");
		//file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($_POST, true) . "\r\n", FILE_APPEND);
		$pubkey = loadX509Cert(PUB_KEY_PATH);
		if ($_POST) {
			$str = $_POST;
			$sign = $str['sign']; //签名
			$signType = $str['signType']; //签名方式
			$data = stripslashes($str['data']); //支付数据
			$charset = $str['charset']; //支付编码
			$result = json_decode($data, true); //data数据
			file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($result, true) . "\r\n", FILE_APPEND);
			//try {
			//verify($data, $sign, $pubkey);
			if ($result['body']['orderStatus'] == "1" || $result['head']['respCode'] == "000000") {

				$OrderID = $result['body']['orderCode'];
				$Amt = intval($result['body']['totalAmount']);
				$Amt = round($Amt / 100, 2);
				file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "回调成功，OrderID：{$OrderID}，Amt：{$Amt}\r\n", FILE_APPEND);
				$this->notify_ok_dopay($OrderID, $Amt);
			}
			echo "respCode=000000";
			exit;
			/*
			  } catch (Exception $e) {
			  file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "失败\r\n", FILE_APPEND);
			  //签名验证失败
			  exit;
			  } */
		}
	}

	/*	 * *********************************************************** */

	//sanfang pay

	public function sanfang_pay($data, $type) {
		require(__DIR__ . '/../../../pay/newpay/config.php');
		require(__DIR__ . '/../../../pay/newpay/lib.php');


		/*
		  "NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/juhenotify.html", //异步通知地址
		  //"ReturnUrl" => "http://" . $_SERVER['SERVER_NAME'] . "/index/user/index.html", //同步返回地址
		  "ReturnUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步返回地址
		 * 		 */
		$data = array(
			"partner" => partner,
			//"md5key"	=> $md5key,  
			"pay_input_charset" => '1',
			"pay_service_type" => $type, //业务类型  1:PC网银收银台  2:PC网银直连  3:wap网银  4:微信扫码  5:支付宝扫码  6:微信WAP支付  7:支付宝WAP支付  8:微信公众号支付  9:QQ钱包扫码  10:QQ钱包WAP支付
			"pay_date" => time(), //订单日期 提交的当前时间的时间戳，格式为time(),例：1508394281
			"pay_order_id" => $data['balance_sn'], //交易订单号  数字，保证系统唯一
			"pay_product_name" => "充值" . time() . "费用", //商品名称
			"pay_amount" => $data['bpprice'] * 100, //交易金额  单位：分，最低1分   例：1元则提交100
			"pay_notify_url" => "http://{$_SERVER['HTTP_HOST']}/index/pay/sanfang_callback.html", //异步回调地址  http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
			"pay_return_url" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步回调地址  http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
		);
		$key = md5key;
		$sign = createSign($data, $key);

		$data['pay_sign'] = $sign; //签名字符串  Md5签名结果
		$data['pay_bank_code'] = ""; //银行编码   业务类型为1时，必填
		$data['pay_remark'] = ""; //备注信息
		$data['pay_extend1'] = ""; //保留域1
		$data['pay_extend2'] = ""; //保留域2
		//$data['pay_extend3'] = '1111';
		//$rs = httpClient($data,PAY_URL);
		$rs = request_form($data, PAY_URL);
		return $rs;
		//var_export($rs);
	}

	public function sanfang_callback() {
		require(__DIR__ . '/../../../pay/newpay/config.php');
		require(__DIR__ . '/../../../pay/newpay/lib.php');
		file_put_contents("sanfang_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($_POST, true) . "\r\n", FILE_APPEND);
		@$pay_order_id = $_POST['pay_order_id'];
		@$pay_amount = $_POST['pay_amount'];
		@$pay_remark = $_POST['pay_remark'];
		@$pay_product_name = $_POST['pay_product_name'];
		@$sign = $_POST['sign'];

		$data = array(
			"pay_order_id" => $pay_order_id,
			"pay_amount" => $pay_amount,
			"pay_remark" => $pay_remark,
			"pay_product_name" => $pay_product_name
		);
		$chesign = createSign($data, md5key);
		if ($sign === $chesign) {
			file_put_contents("sanfang_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "订单号：" . $pay_order_id . "\r\n", FILE_APPEND);
			$OrderID = $pay_order_id;
			$Amt = ($pay_amount);
			//$Amt = round($Amt / 100, 2);
			$this->notify_ok_dopay($OrderID, $Amt);
			echo 'ok';
		} else {
			logResult("异步签名错误");
			echo 'error';
		}
	}

	/*	 * ****************************************************************** */

	public function getClientIp() {
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $ip, $onlineipmatches);
		$ip = empty($onlineipmatches[0]) ? 'unknown' : $onlineipmatches[0];
		return $ip;
	}

}
